package cn.kgc.filter;

import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author: 张晴
 * @date: 2022/2/13
 * @description:
 */
@WebFilter(urlPatterns = {"/view/*"})
public class LoginFilter implements Filter {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //校验用户登录状态
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取Headers中的参数
        String token = request.getHeader("token");
        token = token == null ? "" : token;

        //查询token在Redis中的剩余时间
        Long expire = redisTemplate.getExpire(token);
        if (expire > 0) { //是登录状态
            //重置token的时间
            redisTemplate.expire(token, 30L, TimeUnit.MINUTES);

            //放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //退出登录
            servletRequest.getRequestDispatcher("/login").forward(servletRequest, servletResponse);
            return;
        }
    }

    @Override
    public void destroy() {

    }

}
